from __future__ import division
import matplotlib.pyplot as plt
import numpy
import json
import datetime
import time
import os
import smtplib
from email.mime.multipart import  MIMEMultipart
from email.mime.image import MIMEImage
from numpy import random


def make_barh_text(barh_data_obj):
    for index_barh in range(len(barh_data_obj)):
        width = barh_data_obj[index_barh].get_height()
        height = barh_data_obj[index_barh].get_width()
        text_hight = height + height/40
        if len(str(height)) < 2:
            text_hight = 12*height
        if len(str(height)) == 2:
            text_hight = 4 * height
        if len(str(height)) == 3:
            if int(str(height)[0]) < 3:
                text_hight = 1.6 * height
            if (int(str(height)[0]) <= 5) and (int(str(height)[0]) > 3):
                text_hight = 1.2 * height
            if (int(str(height)[0]) <= 8) and (int(str(height)[0]) > 5):
                text_hight = 1.1 * height
        plt.text(text_hight , barh_data_obj[index_barh].get_y() + width / 3, str(height), ha='center',
                     va='bottom', fontsize='8')


def draw_pict(read_path):
    time_today = str(datetime.datetime.now().strftime("%Y-%m-%d"))
    time_today_hour = str(datetime.datetime.now().strftime("%H:%M"))
    time_yesterday = str((datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d"))

    # 1. Data Machine_Usage picture
    if read_path == 'morning':
        file_path1 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/data_json/'
        file_path2 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/'
    elif read_path == 'night':
        time_yesterday = str((datetime.datetime.now() + datetime.timedelta(days=0)).strftime("%Y-%m-%d"))
        file_path1 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/data_json/night/'
        file_path2 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/data_json/night/img/'
    BJ_tag = 0
    if os.path.isfile(file_path1 + '%s_machine_usage.json' % time_today):
        with open(file_path1 + '%s_machine_usage.json' % time_today, 'r') as f1:
            dict_machine_use = json.load(f1)
        a = list(xrange(0, len(dict_machine_use['All_run'])))
        all_run = dict_machine_use['All_run']
        Katana = dict_machine_use['Katana']
        MR = dict_machine_use['MR']
        if 'BJ' in dict_machine_use.keys():
            BJ = dict_machine_use['BJ']
            BJ_tag = 1
        # ========================================================================================Start Change 2019,7.17
        # to add am and pm
        for index_time,i in enumerate(dict_machine_use["Time"]):
            if int(str(i)) < 12:
                dict_machine_use["Time"][index_time]= str(int(i)) + 'am'
            elif int(str(i)) == 12:
                dict_machine_use["Time"][index_time] = str(int(i)) + 'pm'
            elif 13 <= int(str(i)) <= 23:
                dict_machine_use["Time"][index_time] = str(int(i)-12) + 'pm'
            elif int(str(i)) == 0:
                dict_machine_use["Time"][index_time] = str(int(i)) + 'am'
        # ========================================================================================End
        Time = dict_machine_use['Time']
    else:
        print 'No this json data!!!!!!!'
        a = list(xrange(0, 24))
        all_run = random.randint(1, size=24)
        Katana = random.randint(1, size=24)
        MR = random.randint(1, size=24)
        BJ = random.randint(1, size=24)
        Time = a

    # 2. Data Sequence info picture
    with open(file_path1 + "%s_seq.json" % time_today, 'r') as f2:
        dict_make_seq = json.load(f2)
        # for i in [key for key, item in dict_make_seq.items()]:
        #     print i
        #     # if not i.isdigit():
        #     #     dict_make_seq.pop(i)
        # print dict_make_seq
    index_x = []
    y_block = []
    y_failed = []
    y_run = []
    y_pend = []
    y_complete = []
    for key, item in dict_make_seq.items():
        index_x.append(key)
        y_complete.append(item["complete"])
        y_pend.append(item["pending"])
        y_run.append(item["run"])
        y_failed.append(item["failed"])
        y_block.append(item["block"])
    index = numpy.arange(len(index_x))
    y_array_c = numpy.array(y_complete)
    y_array_p = numpy.array(y_pend)
    y_array_r = numpy.array(y_run)
    y_array_f = numpy.array(y_failed)
    y_array_b = numpy.array(y_block)
    y_all = y_array_b + y_array_p + y_array_f + y_array_r + y_array_c

    y_comp_max = max(y_complete)
    y_pend_max = max(y_pend)
    y_run_max = max(y_run)
    y_failed_max = max(y_failed)
    y_block_max = max(y_block)
    max_y = max([y_comp_max, y_pend_max, y_pend_max, y_failed_max, y_block_max])

    def make_bar_text(bar_data_obj):
        for index_c in range(len(bar_data_obj)):
            height = bar_data_obj[index_c].get_height()
            num = '{:.0%}'.format(height / y_all[index_c])
            if num == '0%':
                num = ''
            plt.text(bar_data_obj[index_c].get_x() + bar_data_obj[index_c].get_width() / 2, height + 5, str(num),
                     ha='center',
                     va='bottom', fontsize=6.8)

    def make_line_text(x,y):
        for a,b in zip(x,y):
            plt.text(a,b+(b/30),b,ha='center',va='bottom',fontsize=6)

    # 3. Data Time avg
    with open(file_path1 + '%s_time.json' % time_today, 'r') as f3:
        dict_time_use = json.load(f3)
    subjob_time_y = []
    sub_comp_number_x = []
    for key, value in dict_time_use.items():
        subjob_time_y.append(key + 'h')
        sub_comp_number_x.append(value)

    # 4. Data Subjob
    with open(file_path1 + '%s_type_submit.json' % time_today, 'r') as f4:
        dict_type_submit = json.load(f4)
    job_type_y = []
    sub_number_x = []
    for key, value in dict_type_submit.items():
        job_type_y.append(key)
        sub_number_x.append(value)

    # 5. Data PIE
    with open(file_path1 + '%s_status_all.json' % time_today, 'r') as f5:
        dict_all_status = json.load(f5)
    pie_data = []
    labels = [u'complete', u'block', u'pending', u'run', u'failed']
    for i in labels:
        pie_data.append(dict_all_status[i])

    # figure mother
    fig = plt.figure()
    fig.set_size_inches(15, 14, forward=True)

    # 1. Machine_Usage picture
    plt.subplot2grid((4, 3), (0, 0), colspan=3)
    plt.plot(a, all_run, marker='.', ms=8, label=u'Run', color='green')
    plt.plot(a, Katana, marker='.', ms=8, label=u'Ka', color='chocolate')
    plt.plot(a, MR, marker='.', ms=8, label=u'MR', color='blue')
    if BJ_tag:
        plt.plot(a, BJ, marker='.', ms=8, label=u'BJ', color='red')
    plt.grid()
    make_line_text(a, all_run)
    make_line_text(a,MR)
    make_line_text(a, Katana)
    if BJ_tag:
        make_line_text(a, BJ)
    plt.xticks(a,Time, fontsize='small')
    plt.xlabel("Time(o'clock)", fontsize='small')
    plt.ylim(ymax=max(all_run)+100)
    legend = plt.legend()
    frame = legend.get_frame()
    label_set_text = legend.get_texts()
    plt.setp(label_set_text, fontsize='small')
    frame.set_alpha(0.3)
    frame.set_facecolor('powderblue')
    plt.ylabel('machine_number')
    plt.title("Machine_Usage[%s 9:00 - %s %s]"%(time_yesterday,time_today,time_today_hour),fontsize='small')

    # 2. Sequence info picture
    plt.subplot2grid((4, 3), (1, 0), colspan=3)
    bar_comp = plt.bar(index - 0.3, y_complete, width=0.1, color='cornflowerblue',edgecolor='cornflowerblue', label=u'complete', alpha=1)
    bar_pend = plt.bar(index - 0.2, y_pend, width=0.1, color='linen',edgecolor='linen', label=u'pend', alpha=1)
    bar_failed = plt.bar(index - 0.1, y_failed, width=0.1, color='red',edgecolor='red', label=u'failed', alpha=1)
    bar_run = plt.bar(index, y_run, width=0.1, color='greenyellow', edgecolor='greenyellow', label=u'run', alpha=1)
    bar_block = plt.bar(index + 0.1, y_block, width=0.1, color='gold',edgecolor='gold', label=u'block', alpha=1)
    legend_bar = plt.legend(loc=0)
    label_set = legend_bar.get_frame()
    label_set_text = legend_bar.get_texts()
    plt.setp(label_set_text,fontsize='small')
    label_set.set_alpha(0.3)
    label_set.set_facecolor('powderblue')
    plt.xticks(range(len(index_x)), index_x,rotation=90,fontsize='small')
    plt.ylim(ymax=max_y + 300)  # to make ylim
    plt.xlim(-1)
    make_bar_text(bar_comp)
    make_bar_text(bar_pend)
    make_bar_text(bar_block)
    make_bar_text(bar_run)
    make_bar_text(bar_failed)
    plt.ylabel('subjob')
    import qb_database
    q = qb_database.QubeDatabase()
    bj_count_r, bj_count_p = q.Bj_subjob_count()
    plt.title("Sequence situation ( BJ : Running-%s  Pending-%s )"%(bj_count_r,bj_count_p),fontsize='small')

    # 3. Render Time situation
    plt.subplot2grid((4, 3), (2, 0), colspan=3)
    barh = plt.barh(numpy.arange(len(subjob_time_y)), sub_comp_number_x, align='center', color='c', edgecolor='c')
    plt.yticks(range(len(subjob_time_y)), subjob_time_y,fontsize='small')
    plt.xlim(xmax=max(sub_comp_number_x) + max(sub_comp_number_x) / 20)
    plt.ylim(-1)
    plt.xlabel('The number of subjob',fontsize='small')
    plt.ylabel('Time use')
    plt.title('Frame_time_use',fontsize='small')
    make_barh_text(barh)

    # 4. Subjob picture
    plt.subplot2grid((4, 3), (3, 0), colspan=2)
    barh = plt.barh(numpy.arange(len(job_type_y)), sub_number_x,align='center', color='y',edgecolor='y')
    plt.yticks(range(len(job_type_y)), job_type_y,fontsize='small')
    if len(sub_number_x) == 0:
        sub_number_x = [0]
    plt.xlim(xmax=max(sub_number_x) + max(sub_number_x)/20)
    plt.xlabel('The number of subjob',fontsize='small')
    plt.title('The type of subjob submit',fontsize='small')
    make_barh_text(barh)

    # 5. PIE picture
    plt.subplot2grid((4, 3), (3, 2), colspan=1)
    colors = ['cornflowerblue', 'gold', 'linen', 'green', 'red']
    explode = (0.05, 0, 0, 0, 0)
    plt.pie(pie_data, colors=colors, explode=explode, labeldistance=1.1, autopct='%3.0f%%', shadow=False,
            startangle=90, pctdistance=0.6)
    plt.title("The Render situation")
    plt.xlabel("Date:%s" % time_yesterday)
    if read_path == 'morning':
        plt.suptitle("Daily Report(%s 09:00-%s %s)"%(time_yesterday,time_today,time_today_hour))
    plt.suptitle("Daily Report(%s 00:00-%s %s)" % (time_yesterday, time_today, time_today_hour))
    plt.subplots_adjust(top=0.93, hspace=0.4)
    # plt.show()
    plt.savefig(file_path2+"%s.jpg"%time_today)
    print 'draw_is_ok'


def send_maile(read_path):
    time_today = str(datetime.datetime.now().strftime("%Y-%m-%d"))
    msg_to = ['chenqx@base-fx.com','pranjan@base-fx.com','xuxx@base-fx.com', 'wanglx@base-fx.com', 'adeosthale@base-fx.com', 'wenggui@base-fx.com', 'haojw@base-fx.com','james.xiao@base-fx.com','wangdh@base-fx.com','mengyan1@base-fx.com']
    # msg_to = ['chenqx@base-fx.com',]
    msg = MIMEMultipart()
    msg['From'] = 'chenqx@base-fx.com'
    msg['To'] = ','.join(msg_to)
    if read_path == 'night':
        msg['Subject'] = 'Render report : Today'
        file_path = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/data_json/night/img/'+'%s.jpg'%time_today
    elif read_path == 'morning':
        msg['Subject'] = 'Render report : Yesterday'
        file_path = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/daily_report/' + '%s.jpg' % time_today
    if os.path.isfile(file_path):
        image = MIMEImage(open(file_path, 'rb').read())
        image.add_header('Content_ID', '<image>')
        msg.attach(image)
    else:
        print 'no daliy jpg '
    server = smtplib.SMTP()
    server.connect('imap.base-fx.com')
    server.login('chenqx@base-fx.com', '587hh*12')
    server.sendmail(msg['From'], msg['To'].split(','), msg.as_string())
    server.quit()
    print 'send_is_ok'


def main(read_path):
    draw_pict(read_path)
    send_maile(read_path)

if __name__ == "__main__":
    # main('morning')
    while True:
        current_time = time.localtime(time.time())
        if ((current_time.tm_hour == 9) and (current_time.tm_min == 30) and (current_time.tm_sec == 0)):
            try:
                main('morning')
            except:
                print 'waiting date........'
                time.sleep(600)
                main('morning')
    
        if ((current_time.tm_hour == 18) and (current_time.tm_min == 40) and (current_time.tm_sec == 0)):
            try:
                main('night')
            except:
                print 'waiting date........'
                time.sleep(600)
                main('night')
        time.sleep(1)


